package com.kehutong.crm.service.impl;

import com.kehutong.common.errcode.Result;
import com.kehutong.crm.entity.DemandForecastSequence;
import com.kehutong.crm.service.DemandForecastSequenceService;
import org.coraframework.inject.Inject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.connection.ThreadLocalCache;
import org.coraframework.util.Objects;

import java.util.*;

/**
 * 需求预测排序服务接口实现类
 *
 * @author wupengfei
 */
public class DemandForecastSequenceServiceImpl implements DemandForecastSequenceService {

    private static final Logger logger = LoggerFactory.getLogger(DemandForecastSequenceServiceImpl.class);

    @Inject
    private JdbcSession jdbcSession;

    @Override
    public void save(String corpId, String userId, long sequence, String type) {
        logger.info("保存需求预测排序corpId=" + corpId + ",userId=" + userId + ",sequence=" + sequence + ",type=" + type);
        save(Collections.singletonList(corpId), userId, sequence, type);
    }

    @Override
    public void save(List<String> corpIdList, String userId, long sequence, String type) {
        logger.info("保存需求预测排序corpIdList=" + corpIdList + ",userId=" + userId + ",sequence=" + sequence + ",type=" + type);
        List<DemandForecastSequence> demandForecastSequenceList = jdbcSession.findArray(DemandForecastSequence.class)
                .in("corpId", corpIdList).and().eq("userId", userId).and().eq("type", type).exe();
        Set<String> corpIdUserSet = new HashSet<>();
        if (Objects.nonEmpty(demandForecastSequenceList)) {
            for (DemandForecastSequence each : demandForecastSequenceList) {
                corpIdUserSet.add(each.getCorpId() + "_" + each.getUserId() + "_" + type);
            }
        }
        List<DemandForecastSequence> insertList = new ArrayList<>();
        for (String each : corpIdList) {
            if (!corpIdUserSet.contains(each + "_" + userId + "_" + type)) {
                DemandForecastSequence demandForecastSequence = Pool.newInstance(DemandForecastSequence.class);
                demandForecastSequence.setSequence(sequence);
                demandForecastSequence.setCorpId(each);
                demandForecastSequence.setUserId(userId);
                demandForecastSequence.setType(type);
                insertList.add(demandForecastSequence);
            }
        }
        if (insertList.size() > 0) {
            jdbcSession.insert(insertList);
        }
    }

    @Override
    public Object rearrange(String id) {
        logger.info("重排序id=" + id);

        // 校验数据
        if (Objects.isBlank(id)) {
            logger.info("参数有误");
            return Result.badArgument();
        }

        // 查询数据
        List<String> idList = Arrays.asList(id.split("\\s*,\\s*"));
        List<DemandForecastSequence> demandForecastSequenceList = jdbcSession.findArray(DemandForecastSequence.class).in("id", idList).and().eq("corpId", ThreadLocalCache.current().getCorpId()).exe();
        if (Objects.isEmpty(demandForecastSequenceList) || idList.size() != demandForecastSequenceList.size()) {
            logger.info("参数有误");
            return Result.badArgument();
        }
        demandForecastSequenceList.sort(Comparator.comparingLong(DemandForecastSequence::getSequence));

        // 设置排序值
        Map<String, Long> idSequenceMap = new HashMap<>();
        for (int i = 0; i < idList.size(); i++) {
            DemandForecastSequence demandForecastSequence = demandForecastSequenceList.get(i);
            idSequenceMap.put(idList.get(i), demandForecastSequence.getSequence());
        }

        // 更新db
        for (DemandForecastSequence each : demandForecastSequenceList) {
            each.setSequence(idSequenceMap.get(each.getId()));
        }
        jdbcSession.updateById(demandForecastSequenceList);
        return Result.success();
    }

}
